from flask import Blueprint, url_for, render_template, request, current_app,redirect, session, flash
from app import db
from app.utils.common import login_required
from app.utils.util import create_nonce_str, create_password
from app.models import Admin
from app.constants import PAGE_LIMIT
from app.forms import AdminForm, LoginForm
from datetime import datetime

admin_controller = Blueprint("admin", __name__)

@admin_controller.route("/")
@login_required
def index():
    print(current_app)
    return render_template("admin/index.html")

@admin_controller.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm(username='admin', password='admin')
    if request.method == 'POST':
        if form.validate_on_submit():
            username = form.data.get('username')
            password = form.data.get('password')
            
            try:
                admin = Admin.query.filter_by(username=username).first()
            except Exception as e:
                flash(str(e))

            if admin:
                if create_password(password, admin.salt) == admin.password:
                    session['user_id'] = admin.id
                    session['username'] = admin.username
                    current_app.username = username
                    return redirect(url_for('admin.admin'))
            flash("用户名或密码不正确")

    return render_template("admin/login.html", form=form)


@admin_controller.route("/admin/logout")
@login_required
def logout():
    session['user_id'] = 0
    session['username'] = ""
    return redirect(url_for('admin.login'))

@admin_controller.route("/admin/index", methods=["GET"])
@login_required
def admin():
    page = request.args.get("page", 1, type=int)
    try:
        pagination = Admin.query.order_by(Admin.id.desc()).paginate(page, per_page=PAGE_LIMIT)
    except Exception as e:
        current_app.logger.error(e)
        flash("获取管理员失败")
    
    return render_template("admin/user/index.html", pagination=pagination)

@admin_controller.route("/admin/add", methods=['GET', 'POST'])
@login_required
def add_admin():
    form = AdminForm()
    if request.method == "POST":
        if form.validate_on_submit():
            username = form.data.get('username')
            password = form.data.get('password')
            salt = create_nonce_str()
            password = create_password(password, salt)
            try:
                admin = Admin(username=username, password=password, salt=salt)
                db.session.add(admin)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                flash("添加管理员失败")
            return redirect(url_for('admin.admin'))
        
    return render_template("admin/user/add.html", form=form)

@admin_controller.route("/admin/edit", methods=['GET', 'POST'])
@login_required
def edit_admin():
    id = request.args.get("id", 0)
    try:
        admin = Admin.query.filter_by(id=id).first()
    except Exception as e:
        current_app.logger.error(e)
        flash("管理员不存在")
        return redirect(url_for('admin.admin'))

    form = AdminForm()
    if request.method == "POST":
        if form.validate_on_submit():
            username = form.data.get('username')
            password = form.data.get('password')
            admin.username = username
            admin.update_time = datetime.now()
            if password:
                salt = create_nonce_str()
                password = create_password(password, salt)
                admin.salt = salt
                admin.password = password
            try:
                db.session.add(admin)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                flash("编辑管理员失败")
            return redirect(url_for('admin.admin'))
        
    return render_template("admin/user/edit.html", form=form, admin=admin)

@admin_controller.route("/admin/delete", methods=['GET'])
@login_required
def del_admin():
    id = request.args.get("id", 0, type=int)
    if id == 1:
        flash("超级管理员不能删除")
        return redirect(url_for('admin.admin'))
    try:
        admin = Admin.query.filter_by(id=id).first()
    except Exception as e:
        current_app.logger.error(e)
        flash("管理员不存在")
        return redirect(url_for('admin.admin'))

    try:
        db.session.delete(admin)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        flash("删除管理员失败")

    return redirect(url_for('admin.admin'))

